package scoping.helpers;

import scoping.ScopeTree;
import scoping.blocks.ClassScope;
import scoping.blocks.ScopeBlock;
import ic.ast.decl.DeclClass;
import ic.ast.decl.DeclMethod;
import ic.ast.decl.Type;

public class VariableLocation {
	private Type type;
	private ScopeTree scopeTree;
	private int register;
	
	public static VariableLocation getVariableScope(ScopeTree tree, String varName){
		while (tree != null) {
			Type type = tree.getBlock().getVariable(varName);
			if (type != null){
				int register = tree.getBlock().getVariableRegister(varName);
				return new VariableLocation(type, tree, register);
			}
			tree = tree.getParent();
		}
		return null;
	}
	
	public static DeclMethod getClassMethod(DeclClass declClass, String methodName){
		while (declClass != null){
			for (DeclMethod declMethod:declClass.getMethods()){
				if (declMethod.getName().equals(methodName)){
					return declMethod;
				}
			}
			ScopeBlock parent = declClass.getScope().getParent().getBlock();
			ClassScope parentClassScope = parent instanceof ClassScope ? (ClassScope)parent : null;
			declClass = parentClassScope != null ? parentClassScope.getClassDeclaration() : null;
		}
		return null;
	}
	
	public VariableLocation(Type type, ScopeTree scopeTree, int register){
		this.type = type;
		this.scopeTree = scopeTree;
		this.register = register;
	}

	public Type getType() {
		return type;
	}

	public ScopeTree getScopeTree() {
		return scopeTree;
	}
	
	public int getRegister(){
		return register;
	}
}
